"""
    python中异常的处理
    try：可能出现异常的代码（必要）
    except：出现异常后执行的代码（必要）
    else：没有出现异常后执行的代码（非必要）
    finally：不论有没有异常，都会执行的代码（非必要）
    打印为定义的变量
    print(name)
报错内容：
  Traceback (most recent call last):
  File "D:\\pythonWorkspace\\6_python的异常.py", line 9, in <module>
    print(name)
          ^^^^
NameError: name 'name' is not defined
"""

"""
    捕获该异常(捕获所有异常)  
        方式一：except
        方式二：except Exception as e
"""
# 方式一
try:
    print(name)
except:
    print("name未定义")

# 方式二
try:
    print(name)
except Exception as e:
    print(e)
    print("name未定义")

"""
    捕获该异常(捕获具体异常)  
        方式一：except NameError
"""
try:
    print(name)
except NameError:
    print("name未定义")

try:
    print(name)
except NameError as e:
    print(e)
    print("name未定义")

"""
    捕获该异常,并处理该异常
        方式一：except
        方式二：except Exception as e
"""
name = '旧name'
try:
    print(name)
except NameError:
    name = '张三'
else:
    print(f"原名字为：{name}")
finally:
    print(f"最终的名字为：{name}")

"""
    捕获多个异常
    NameError：变量未定义异常
    FileNotFoundError：文件未找到异常
"""
# f = open("D:\\wide.txt", 'r', encoding="UTF-8")
file = "D:\\wide.txt"
try:
    f = open(file, 'r', encoding="UTF-8")
except NameError:
    print("变量未定义")
except FileNotFoundError:
    print("文件不存在")


"""
所有关键字的使用
    try、except、else、finally
"""
try:
    print(name2)
except:
    print("name2未定义")
else:
    print("没有出现异常")
finally:
    print("异常捕获执行结束")





